<template>
  <div class="chat_view_box">
    <div class="chat_view" ref="view">
      <ul>
        <li class="message_box" v-for="(item,index) in result" :key="index">
          <div class="user_left" v-if="item.username!=username">
            <div class="user">
              <img :src="item.picture" alt="...">
              <span>{{item.name}}:</span>
            </div>
            <div class="message">
              <span class="mini"></span>
              <span class="text" v-html="item.content"></span>
            </div>
          </div>
          <div class="user_right" v-else>
            <div class="message">
              <span class="mini"></span>
              <span class="text" v-html="item.content"></span>
            </div>
            <div class="user">
              <span>:{{item.name}}</span>
              <img :src="item.picture" alt="...">
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Chatview',

  data() {
    return {
      result: [] // 展示消息数据集
    };
  },

  props: {
    // 新消息对象
    message: Object
  },

  watch: {
    message(newVal){
      if(newVal){
        this.result.push(newVal)
        this.$nextTick(() => {
          let view = this.$refs.view
          view.scrollTop = view.scrollHeight
        })
      }
    }
  },

  computed: {
    // 返回当前登录用户名
    username(){
      return this.$store.state.userinfo ? this.$store.state.userinfo.username : ''
    }
  },
};
</script>

<style scoped>
.chat_view_box{
  width: 100%;
  max-height: 90vh;
  overflow: hidden;
  border: 1px solid gray;
  background-color: white;
}
.chat_view{
  width: 100%;
  height: 60vh;
  min-height: 300px;
  margin-left: 17px;
  overflow-y: scroll;
  padding: 10px 30px 10px 10px;
}

.message_box .user_left,.user_right{
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.user_left{
  justify-content: flex-start;
}
.user_right{
  justify-content: flex-end;
}
.message_box .user{
  display: flex;
  align-items: center;
  color: gray;
  letter-spacing: 2px;
}
.message_box .user img{
  width: 44px;
  height: 44px;
  border-radius: 50%;
}
.message_box .user span{
  white-space: nowrap;
}
.message{
  position: relative;
  margin: 0 10px;
}
.message_box .text{
  border: 1.5px solid gray;
  padding: 6px 10px;
  margin: 4px;
  border-radius: 4px;
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
  background-color: white;

}
.message_box .user_right .mini{
  position: absolute;
  top: 45%;
  right: -7px;
  border-color: transparent transparent transparent gray;
  border-width: 6px;
  border-style: solid;
}
.message_box .user_left .mini{
  position: absolute;
  top: 15px;
  left: -7px;
  border-color: transparent gray transparent transparent;
  border-width: 6px;
  border-style: solid;
}
@media screen and (max-width:800px){
  .chat_view_box{
    flex: 1;
  }
  .chat_view{
    height: 50vh;
  }
}
</style>